<template>
  <l-layout class="l-tab-page" v-show="!lr_loadPage">
    <template #left>
      <l-panel :title="$t('功能目录')" style="padding-right: 0">
        <el-tree :data="modulesExpandTree" :expand-on-click-node="false" @node-click="handleNodeClick">
          <span class="lr-tree-node" slot-scope="{ node, data }">
            <i :class="data.icon"></i>
            {{ $t(node.label) }}
          </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input placeholder="请输入" @keyup.enter.native="hanleSearch" v-model="keyWord" size="mini">
            <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()">
          <l-excel-btns></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table
        :loading="tableLoading"
        :columns="columns"
        :dataSource="tableData"
        row-key="f_Id"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
      >
        <template v-slot:f_CreateDate="scope">
          {{ lr_dateFormat(scope.row.f_CreateDate) }}
        </template>
        <template v-slot:f_PModuleId="scope">
          {{ (modules.find((t) => t.f_ModuleId == scope.row.f_PModuleId) || {}).f_FullName || "" }}
        </template>
        <template v-slot:f_EnabledMark="scope">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.f_EnabledMark"
            @change="handleEnableChange(scope.row)"
          >
          </el-switch>
        </template>
        <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick"></l-table-btns>
      </l-table>
    </l-panel>
    <l-fullscreen-dialog
      :title="`${$t('功能设计')}`"
      :headerMidWidth="320"
      :visible.sync="formVisible"
      :isStep="true"
      :steps="['基本配置', '页面设计']"
      :stepActive.sync="stepActive"
      :validateSteps="handleValidateSteps"
      @ok="handleSave"
      @closed="handleClosed"
      @opened="handleOpened"
    >
      <my-form ref="form" :stepActive="stepActive"></my-form>
    </l-fullscreen-dialog>
  </l-layout>
</template>

<script>
import { mapGetters } from "vuex";
const api = window.$api.custmerForm.module;

import MyForm from "./form";
export default {
  inject: ["admin"],
  components: {
    MyForm,
  },
  data() {
    return {
      lr_isPage: true,
      // 设计表单
      stepActive: 0,
      formVisible: false,
      formEdit: false,
      formEditRow: null,

      // 左侧树形
      treeLoading: true,
      treeCategory: "",

      // 表格
      columns: [
        { label: "名称", prop: "f_Name", minWidth: "150" },
        { label: "上级功能", prop: "f_PModuleId", minWidth: "120" },
        { label: "状态", prop: "f_EnabledMark", width: "64", align: "center" },
        { label: "创建人", prop: "f_CreateUserName", width: "100", align: "center" },
        { label: "创建时间", prop: "f_CreateDate", width: "160" },
      ],
      tableLoading: false,
      tableTotal: 0,
      tablePageSize: 50,
      tableCurrentPage: 1,
      tableData: [],
      keyWord: "",
      tableBtns: [
        { prop: "Edit", label: "编辑" },
        { prop: "Delete", label: "删除" },
      ],
    };
  },
  mounted() {
    this.init();
  },
  computed: {
    ...mapGetters(["modules", "modulesExpandTree"]),
  },
  methods: {
    init() {
      this.loadTablePage(true);
    },
    updateModules() {
      this.$store.dispatch("system/module/getList").then(() => {
        this.admin.refreshMenu();
      });
    },
    loadTablePage() {
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: "F_CreateDate",
        keyWord: this.keyWord,
        f_PModuleId: this.treeCategory,
      };
      api
        .getPage(queryData)
        .then((res) => {
          const data = this.$deepClone(res.data.data);
          this.tableData = data.rows;
          this.tableTotal = data.records;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableData = [];
          this.tableLoading = false;
        });
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTablePage(true);
    },
    handleNodeClick(node) {
      this.treeCategory = node.id;
      this.tableCurrentPage = 1;
      this.loadTablePage();
    },
    hanleSearch() {
      this.loadTablePage();
    },
    // 表单部分
    handleAdd() {
      this.formEdit = false;
      this.showForm();
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.showForm();
    },
    handleDelete($index, row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.remove(row.f_Id).then(() => {
            this.tableData.splice($index, 1);
            this.tableTotal--;
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.updateModules();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleEnableChange(row) {
      api.updateState(row.f_Id, row.f_EnabledMark).then(() => {
        this.$message({
          type: "success",
          message: "更新成功!",
        });
        this.updateModules();
      });
    },
    handleSave(showLoading, hideLoading) {
      showLoading("保存数据中...");
      const postData = this.$refs.form.getForm();
      if (this.formEdit) {
        api
          .update(this.formEditRow.f_Id, postData)
          .then(() => {
            this.loadTablePage();
            this.updateModules();
            this.$message({
              type: "success",
              message: "更新成功!",
            });
            this.formVisible = false;
            hideLoading();
          })
          .catch(() => {
            hideLoading();
          });
      } else {
        api
          .add(postData)
          .then(() => {
            this.loadTablePage();
            this.updateModules();
            this.$message({
              type: "success",
              message: "保存成功!",
            });
            this.formVisible = false;
            hideLoading();
          })
          .catch(() => {
            hideLoading();
          });
      }
    },
    showForm() {
      this.formVisible = true;
    },

    handleValidateSteps() {
      return this.$refs.form.validateSteps();
    },

    async handleOpened(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        const data = await this.$awaitWraper(api.get(this.formEditRow.f_Id));

        if (data) {
          this.$refs.form.setForm(data);
        } else {
          this.$message({
            type: "error",
            message: "后端没有返回数据!",
          });
          this.formVisible = false;
        }

        hideLoading();
      }
    },
    handleClosed() {
      this.$refs.form.resetForm();
    },
  },
};
</script>
